<script lang="ts" setup>
import type { EchartsUIType } from '@vben/plugins/echarts';

import { onMounted, ref, watch } from 'vue';

import { EchartsUI, useEcharts } from '@vben/plugins/echarts';

// 导入echarts以解决全局变量问题
import * as echarts from 'echarts';

interface UsageTrendData {
  dates: string[];
  mileage: number[];
  timeUnit?: string;
}

const props = defineProps<{
  data: UsageTrendData;
}>();

const chartRef = ref<EchartsUIType>();
const { renderEcharts } = useEcharts(chartRef);

// 监听数据变化，重新渲染图表
watch(
  () => props.data,
  () => {
    renderChart();
  },
  { deep: true },
);

const renderChart = () => {
  if (!props.data || !props.data.dates || !props.data.mileage) return;

  renderEcharts({
    grid: {
      bottom: 60,
      left: 60,
      right: 20,
      top: 20,
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: props.data.dates,
      axisLabel: {
        interval: 0,
        rotate: props.data.timeUnit === 'day' ? 45 : 0,
      },
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} 公里',
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#e0e0e0',
        },
      },
    },
    series: [
      {
        name: '行驶里程',
        type: 'line',
        data: props.data.mileage,
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          width: 3,
          color: '#5ab1ef',
        },
        itemStyle: {
          color: '#5ab1ef',
          borderColor: '#ffffff',
          borderWidth: 2,
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(91, 177, 239, 0.3)' },
            { offset: 1, color: 'rgba(91, 177, 239, 0.1)' },
          ]),
        },
        emphasis: {
          focus: 'series',
          lineStyle: {
            width: 4,
          },
        },
      },
    ],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#5ab1ef',
        },
      },
      formatter: (params: any) => {
        const data = params[0];
        const unit = props.data.timeUnit === 'day' ? '日' : '月';
        return `
          <div style="padding: 8px;">
            <div style="font-weight: bold; margin-bottom: 4px;">${data.name}${unit}</div>
            <div>行驶里程: <span style="color: #5ab1ef;">${data.value} 公里</span></div>
          </div>
        `;
      },
    },
    animation: true,
  });
};

onMounted(() => {
  renderChart();
});
</script>

<template>
  <div class="h-full w-full">
    <EchartsUI ref="chartRef" />
  </div>
</template>

<style scoped>
/* 图表容器样式 */
.w-full {
  width: 100%;
}

.h-full {
  height: 100%;
}
</style>
